home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14153 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: erich.triumf.ca!bennett
  2. From: bennett@erich.triumf.ca (P.Bennett)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Can anyone help a newbie out ?
  5. Date: 11 Apr 1996 22:54 PST
  6. Organization: TRIUMF: Tri-University Meson Facility
  7. Distribution: world
  8. Message-ID: <11APR199622540287@erich.triumf.ca>
  9. References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
  10. NNTP-Posting-Host: ftp.triumf.ca
  11. News-Software: VAX/VMS VNEWS 1.50    
  12.  
  13. In article <4kkf3r$5b0@darwin.nbnet.nb.ca>, lewwid@brunswickmicro.nb.ca (Jeff) writes...
  14. >I started reading a book on C, and i am stuck on one exercise, and i
  15. >know it's really simple, but i can't do it :(  
  16. >Problem:Write a function that accepts two strings.  Count the number
  17. >of characters in each string, and return the pointer to the longer
  18. >string.
  19. >This is what my lamer brain had to say ...
  20. >#include <stdio.h>
  21. >char *ptr, *ptr1;
  22.  
  23. This reserves space for two pointers-to-char, but does not initialize them to
  24. point anywhere in particular, not does it reserve any space to store chars. 
  25. You probably should say:
  26.     char ptr[80], ptr1[80];
  27. (or change '80' as needed to accomodate the longest expected string.)
  28.  
  29. >    puts("Please enter in the first string :");
  30. >    gets(ptr);
  31.  
  32. Two important points: 
  33.     NEVER use gets(), unless you have a Really Good Reason.
  34.     There is NEVER a good reason to use gets().
  35. Use fgets() instead. (_Always!_)
  36.     fgets(ptr, 80, stdin);
  37.  
  38. >    while (*x != NULL)
  39.  
  40. NULL is the "null pointer constant" and is not a char.  Use:
  41.     while (*x != '\0')
  42. >        total += 1
  43.                           ^ a semicolon is needed here
  44. (there is a strlen() function that will do this for you.)
  45. Also, you aren't stepping through the array.
  46. I would probably do:
  47.     int i = 0
  48.     while(x[i++] != '\0')
  49.             total += 1;
  50.  
  51. >    if (total < total2)
  52. >        return *y;
  53.  
  54. This should be "return y", to return a pointer to one array, *y returns the
  55. first char.
  56.  
  57.  
  58. Peter Bennett VE7CEI                | Vessels shall be deemed to be in sight
  59. Internet: bennett@triumf.ca         | of one another only when one can be
  60. Packet: ve7cei@ve7kit.#vanc.bc.ca   | observed visually from the other
  61. TRIUMF, Vancouver, B.C., Canada     |                          ColRegs 3(k)
  62. GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
  63. or: ftp://ftp-i2.informatik.rwth-aachen.de/pub/arnd/GPS/peter/index.html
  64.  
  65.  
  66.  
  67.  
  68.  
  69.